layui.config({
    base: "/layui/"
}).extend({
    index: 'lib/index'
}).use(['index', 'form', 'jquery', 'table', 'laydate', 'upload'], function () {
    var form = layui.form,
        upload = layui.upload,
        table = layui.table,
        admin = layui.admin,
        laydate = layui.laydate;

    //日期时间选择器
    laydate.render({
        elem: '#begin_time'
        , type: 'datetime'
    });
    //日期时间选择器
    laydate.render({
        elem: '#end_time'
        , type: 'datetime'
    });

    /**
     * 防重复设置
     * @type {boolean}
     */
    var edit_flag = true;

    table.render({
        elem: '#activity_info_table'
        , url: '/activity/queryData'
        , method: "post"
        , height: 500
        , limit: 50							//显示数目
        , limits: [50, 100]
        , cols: [[
            {field: 'id', width: 100, title: 'id', "align": "center"}
            , {field: 'name', width: 180, title: '门店名称', "align": "center"}
            , {field: 'title', width: 220, title: '活动名称', "align": "center"}
            , {field: 'begin_time', width: 240, title: '活动开始时间', "align": "center"}
            , {field: 'end_time', width: 240, title: '活动结束时间', "align": "center"}
            , {
                field: 'state', width: 140, title: '活动状态', "align": "center", templet: function (d) {
                    if (d.state == 0) {
                        return "活动关闭中";
                    } else {
                        return "活动开启中";
                    }
                }
            }
            , {field: 'conver_text', width: 240, title: '封面简介', "align": "center",hide: true}
            , {field: 'icon_url', width: 240, title: '封面图片', "align": "center",hide: true}
            , {field: 'text', width: 240, title: '图文描述', "align": "center",hide: true}
            , {field: 'image_url', width: 240, title: '图片链接', "align": "center",hide: true}
            , {field: 'createdTime', width: 240, title: '活动创建时间', "align": "center"}
            , {field: 'OPT', width: 250, title: '操作', "align": "center", toolbar: "#OptData"}
        ]]
        , request: {
            pageName: 'pageNo' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        where: {}
        , id: 'activity_info_table'
        , page: true
    });

    table.on('tool(activity_info_table)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        if (layEvent === 'modify_activity') { //编辑门店
            $.ajax({
                url: "/enterprise_store/queryData",
                data: {"type": 1},
                type: "post",
                success: function (result) {
                    if (result.code == 1) {
                        $("#storeId").empty();
                        var datas = result.data;
                        $("#storeId").append('<option value="">请选择</option>');
                        for (var i = 0; i < datas.length; i++) {
                            if (datas[i].name != null) {
                                if(datas[i].name == data.name){
                                    $("#storeId").append('<option selected="selected" value="' + datas[i].id + '">' + datas[i].name + '</option>');
                                    continue;
                                }
                                $("#storeId").append('<option value="' + datas[i].id + '">' + datas[i].name + '</option>');
                            }
                        }
                        form.render('select');
                    } else {
                        layer.msg(result.message, {
                            offset: '32%'
                            , icon: 2
                            , time: 3000
                        }, function () {

                        })
                    }
                }
            });
            $('#storeId').attr("disabled","disabled");
            $('#begin_time').attr("disabled","disabled");
            $('#end_time').attr("disabled","disabled");

            $(".icon_url_input").val(data.icon_url);
            $(".icon_url_img").attr('src', data.icon_url); //图片链接（base64）
            $(".image_url_input").val(data.image_url);
            $(".image_url_img").attr('src', data.image_url); //图片链接（base64）

            form.val('add_activity_info_form', {
                "id": data.id,
                "title": data.title,
                "begin_time": data.begin_time,
                "end_time": data.end_time,
                "state": data.state,
                "conver_text": data.conver_text,
                "text": data.text
            });
            admin.popup({
                title: '编辑'
                , shade: 0
                , anim: -1
                , offset: "20px"
                , area: ['60%', '650px']
                , skin: 'layui-anim layui-anim-upbit'
                , content: $("#add_activity_info_win")
                , end: function () {

                }
            });

        } else if (layEvent === 'edit_card') {
            var activityId = data.id;//活动id
            layer.open({
                type: 2,
                area: ['90%', '90%'],
                title: "选择",
                fixed: false, //不固定
                maxmin: true,
                maxmin: false,
                shadeClose: false,
                content: '/cardInfo/index/'+activityId
            });

        }else if(layEvent === 'open_activity'){
            layer.confirm('是否开启此活动?', function (index) {
                $.ajax({
                    url: "/activity/openAndCloseActivity",
                    data: {"id": data.id, "state": 1},
                    type: "post",
                    success: function (result) {
                        if (result.code == 1) {
                            table.reload('activity_info_table', {});
                            layer.closeAll();
                        } else {
                            layer.msg(result.message, {
                                offset: '32%'
                                , icon: 2
                                , time: 3000
                            }, function () {

                            });
                        }
                    }
                });
            });
        }else if(layEvent === 'close_activity'){
            layer.confirm('是否关闭此活动?', function (index) {
                $.ajax({
                    url: "/activity/openAndCloseActivity",
                    data: {"id": data.id, "state": 0},
                    type: "post",
                    success: function (result) {
                        if (result.code == 1) {
                            table.reload('activity_info_table', {});
                            layer.closeAll();
                        } else {
                            layer.msg(result.message, {
                                offset: '32%'
                                , icon: 2
                                , time: 3000
                            }, function () {

                            });
                        }
                    }
                });
            });
        }
    });

    /**
     * 新增与修改活动信息
     */
    $(".activityAdd").click(function () {

        $("#add_activity_info_form")[0].reset();
        layui.form.render();
        $(".image_url_img").attr("src","");
        $(".icon_url_img").attr("src","");
        $('#storeId').removeAttr("disabled");
        $('#begin_time').removeAttr("disabled");
        $('#end_time').removeAttr("disabled");
        $('#id').val(null);
        /**
         * 初始化 门店下拉
         */
        $.ajax({
            url: "/enterprise_store/queryData",
            data: {"type": 1},
            type: "post",
            success: function (result) {
                if (result.code == 1) {
                    $("#storeId").empty();
                    var data = result.data;
                    $("#storeId").append('<option value="">请选择</option>');
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].name != null) {
                            $("#storeId").append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
                        }
                    }
                    form.render('select');
                } else {
                    layer.msg(result.message, {
                        offset: '32%'
                        , icon: 2
                        , time: 3000
                    }, function () {

                    })
                }
            }
        });

        var date = new Date();
        $("#begin_time").val(date); //开始时间

        var year = date.getFullYear(); //获取完整的年份(4位,1970-????)
        var month = date.getMonth(); //获取当前月份(0-11,0代表1月)         // 所以获取当前月份是myDate.getMonth()+1;
        var day = date.getDate(); //获取当前日(1-31)
        var str = (year+1) + "-" + (month+1) + "-" + (day-1) + " 23:59:59"
        $("#end_time").val(str); //结束时间

        admin.popup({
            title: '添加活动'
            , shade: 0
            , anim: -1
            , offset: "20px"
            , area: ['60%', '650px']
            , skin: 'layui-anim layui-anim-upbit'
            , content: $("#add_activity_info_win")
            , end: function () {

            }
        });

    });

    /**
     * 保存活动信息
     */
    form.on('submit(preserve)', function (data) {
        data.field.state = 0;
        $.ajax({
            url: "/activity/edit",
            data: data.field,
            type: "post",
            success: function (result) {
                if (result.code == 1) {
                    layer.msg("保存成功", {
                        offset: '32%'
                        , icon: 1
                        , time: 0
                        , btn: '知道了'
                        , btnAlign: "c"
                        , shade: 0.4
                        , yes: function () {
                            table.reload('activity_info_table', {});
                            layer.closeAll();
                        }
                    })
                } else {
                    layer.msg(result.message, {
                        offset: '32%'
                        , icon: 2
                        , time: 3000
                    }, function () {
                        layer.closeAll();
                    })
                }
            }
        });
        return false;
    });

    $(".search_btn").click(function () {
        table.reload('activity_info_table', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                name: $(".queryTable input[name='name']").val()
            }
        });
    });

    /**
     *     图片简介
     */
    var icon_img_value = $(".icon_url_input").val();
    if (icon_img_value != null && icon_img_value != "" && icon_img_value != undefined) {
        $(".icon_url_img").attr('src', icon_img_value);
    }
    var icon_upload_btn = $(".icon_file_btn");
    var uploadInst = upload.render({
        elem: icon_upload_btn
        , url: '/activity/addConverText'
        , data: {}
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $(".icon_url_img").attr('src', result); //图片链接（base64）
            });
            var conver_text = $('#conver_text').val();
            var id = $('#id').val();
            this.data.conver_text = conver_text;
            this.data.id = id;
        }
        , done: function (res) {
            if (res.code == 1) {
                //如果上传成功
                $(".icon_url_input").val(res.data.icon_url);
                return layer.msg('上传成功');
            } else {
                //上传失败
                $(".icon_url_img").attr('src', ""); //图片链接（base64）
                return layer.msg(res.message);
            }
        }
        , error: function () {
            //演示失败状态，并实现重传
            fade_file_tip.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            fade_file_tip.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });

    /**
     *     图文描述
     */
    var image_url_value = $(".image_url_input").val();
    if (image_url_value != null && image_url_value != "" && image_url_value != undefined) {
        $(".image_url_img").attr('src', image_url_value);
    }
    var image_upload_btn = $(".image_file_btn");
    var uploadInsts = upload.render({
        elem: image_upload_btn
        , url: '/activity/addImageUrl'
        , data: {}
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $(".image_url_img").attr('src', result); //图片链接（base64）
            });
            var text = $('#text').val();
            var id = $('#id').val();
            this.data.text = text;
            this.data.id = id;
        }
        , done: function (res) {
            if (res.code == 1) {
                //如果上传成功
                $(".image_url_input").val(res.data.image_url);
                return layer.msg('上传成功');
            } else {
                //上传失败
                $(".image_url_img").attr('src', ""); //图片链接（base64）
                return layer.msg(res.message);
            }
        }
        , error: function () {
            //演示失败状态，并实现重传
            image_url_tip.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            image_url_tip.find('.demo-reload').on('click', function () {
                uploadInsts.upload();
            });
        }
    });
});

